import {format} from 'date-fns';

export const TS = (seconds ?: number) => seconds ? new Timestamp(seconds) : undefined

export const TSO = (data: any) => {
    if (data.postdatetimestamp && typeof data.postdatetimestamp === 'number') {
        return TS(data.postdatetimestamp)
    }
    if (data.postdate && typeof data.postdate === 'number') {
        return TS(data.postdate)
    }
    if (data.postdate && typeof data.postdate === 'string') {
        return TS(new Date(data.postdate + "+0800").getTime() / 1000)
    }
    console.warn('发布时间识别失败', data)
    return undefined
}

/**
 * 时间戳
 */
export class Timestamp {
    readonly seconds: number
    readonly date: Date
    readonly full: string
    readonly short: string

    diff() {
        return new DatetimeDiff(this.date)
    }

    constructor(seconds: number) {
        const d = new Date(seconds * 1000);
        this.seconds = seconds;
        this.date = d
        this.full = format(d, 'yyyy-MM-dd HH:mm:ss')
        this.short = format(d, 'yy-MM-dd HH:mm')
    }
}

/**
 * 时间差
 */
export class DatetimeDiff {
    readonly seconds: number
    readonly minutes: number
    readonly hours: number
    readonly days: number
    readonly weeks: number
    readonly months: number
    readonly years: number

    constructor(date: Date) {
        this.seconds = Math.floor((new Date().getTime() - date.getTime()) / 1000);
        this.minutes = Math.floor(this.seconds / 60);
        this.hours = Math.floor(this.minutes * 10 / 60) / 10;
        this.days = Math.floor(this.hours * 10 / 24) / 10;
        this.weeks = Math.floor(this.days * 10 / 7) / 10;
        this.months = Math.floor(this.days * 10 / 30) / 10;
        this.years = Math.floor(this.days * 10 / 365) / 10;
    }
}